package com.meitianhui.convenitenbuy.module.home.ui.activity.web;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;

import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseWebViewActivity;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.hyphenate.ui.ChatActivity;
import com.meitianhui.convenitenbuy.main.model.bean.HyphenateInfo;
import com.meitianhui.convenitenbuy.module.home.ui.activity.IntegrationActivity;
import com.meitianhui.convenitenbuy.util.JumpUtil;
import com.meitianhui.convenitenbuy.util.TipUtils;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by Administrator on 2017/11/9.
 */

public class MemberRulesWebViewActivity extends BaseWebViewActivity {

    private String mMemberId;
    private String mMobile;
    private String point="";
    private boolean mIsSecond;
    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        mMemberId= getIntent().getStringExtra("member_id");
        mMobile= getIntent().getStringExtra("mobile");
        mIsSecond = getIntent().getBooleanExtra("is_second",false);
        setTbTitle(mTitle);
        if(mIsSecond){
            setTbMenu("");
        }else{
            setTbMenu(R.mipmap.icon_title_detail);
        }
        mWebView.addJavascriptInterface(new MyJavaScriptInterface(this), "jsObj");//js调用安卓

    }


    //js调用安卓代码
    private class MyJavaScriptInterface {
        private Context mContext;
        private Handler handler = new Handler();
        public MyJavaScriptInterface(Context c) {
            this.mContext = c;
        }



        //返回按钮
        @JavascriptInterface
        public void closeWebView() {
            MemberRulesWebViewActivity.this.finish();
        }

        //打开广告页
        @JavascriptInterface
        public void openAdLayer(final String jsonData) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    try {
                        JSONObject jsonObject = new JSONObject(jsonData);
                        String url = jsonObject.getString("url");
                        Intent intent = new Intent(MemberRulesWebViewActivity.this, AdWebViewActivity.class);
                        intent.putExtra("url", url);
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            });
        }
        //点击跳到选择免单券和积分
        @JavascriptInterface
        public void getGoodsInfo(final String jsonData,final String activityId) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    if(!TextUtils.isEmpty(jsonData)){
                        try {
                            JSONObject jsonObject=new JSONObject(jsonData);
                            point=jsonObject.getString("limited_point");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        if(Integer.parseInt(point)>Integer.parseInt(InfoProvider.getUserAsset(App.getInstance()).getBonus())){
                            TipUtils.showToast(App.getInstance(),"您的积分不足，无法兑换该商品！");
                            return;
                        }
                        Intent intent=new Intent(MemberRulesWebViewActivity.this, IntegrationActivity.class);
                        intent.putExtra("json",jsonData);
                        intent.putExtra("activity_id",activityId);
                        startActivityForResult(intent, 0);
                    }
                }

            });
        }

        //客服功能
        @JavascriptInterface
        public void chatWithCustomerServiceAgent(final String chat) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (!InfoProvider.getLoginStatus(MemberRulesWebViewActivity.this)) {
                            JumpUtil.jumpToLoginActivity(0, MemberRulesWebViewActivity.this, 0, "");
                            return;
                        }
                        HyphenateInfo hyphenateInfo = InfoProvider.getHyphenateInfo(MemberRulesWebViewActivity.this);
                        if(hyphenateInfo==null){
                            return;
                        }
                        String imUserId = hyphenateInfo.getIm_user_id();
                        if (TextUtils.isEmpty(imUserId)) {
                            return;
                        }
                        JSONObject jsonObject = new JSONObject(chat);
                        final String chatId = jsonObject.getString("chat_id");
                        final String title = jsonObject.getString("title");
                        Intent intent = new Intent(MemberRulesWebViewActivity.this, ChatActivity.class);
                        intent.putExtra("userId", chatId);
                        intent.putExtra("groupName", title);
                        startActivity(intent);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, 0);
        }
    }
    @Override
    protected void clickMenu() {
        super.clickMenu();
        Intent intent = new Intent(MemberRulesWebViewActivity.this, MemberRulesWebViewActivity.class);
        intent.putExtra("url", Constants.HOST + "h5/c/interests/history"
                + "?member_id=" + mMemberId+"&mobile="+mMobile);
        intent.putExtra("title", "历史记录");
        intent.putExtra("member_id",mMemberId);
        intent.putExtra("is_second",true);
        intent.putExtra("mobile",mMobile);
        startActivity(intent);
    }

    @Override
    protected void urlLoading(WebView view, String url) {
        view.loadUrl(url);
    }

    @Override
    protected void receivedTitle(WebView view, String title) {
        if(!title.contains("about:blank")){
            mTb_title.setText(title);
        }
    }

    @Override
    protected void onRefreshData() {

    }

    @Override
    protected void isFinish() {
        if (mWebView.canGoBack() && !"about:blank".equals(mWebView.getUrl())) {
            mWebView.goBack();// 返回前一个页面
        } else {
            finish();
        }
    }

    @Override
    protected void shareWxMini(View v) {

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack() && !"about:blank".equals(mWebView.getUrl())) {
            mWebView.goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if( mWebView.canGoBack()){
                mWebView.goBack();
            }
        }
    }
}
